import sys
import csv
# 功能打印
def print_menu():
    print('*' * 30)
    print('欢迎使用通讯录管理系统')
    print('1.新建联系人')
    print('2.显示通讯录')
    print('3.删除联系人')
    print('4.修改联系人信息')
    print('5.查找联系人')
    print('6.退出系统')
    print('*' * 30)

#定义一个判断通讯录.csv表头是否存在的函数
def header_exists(expected_header):
    try:
        with open('通讯录.csv', 'rt',encoding='utf-8') as csvfile:
            csv_reader = csv.reader(csvfile)
            existing_header = next(csv_reader, None)  # Read the first line of the file
            return existing_header == expected_header
    except FileNotFoundError:
        return False  # 文件不存在，因此表头肯定不存在

# 1. 定义一个添加联系人的函数
def create_contact():
    rows =[]
    while True:
        per_name = input('请输入联系人的姓名:')
        phone_num = input('请输入联系人的手机号码:')
        QQ_num = input('请输入联系人的QQ号:')
        per_email = input('请输入联系人的邮箱:')
        row = {"姓名": per_name, "手机号码": phone_num,"QQ号": QQ_num,"邮箱": per_email}
        rows.append(row)
        print(f"成功添加{per_name}为联系人")
        continue_confirm = input('还需要继续添加联系人吗？(Y or N):')
        if continue_confirm == 'Y' or continue_confirm == 'y':
            continue
        else:
            break

    header = ['姓名', '手机号码', 'QQ号', '邮箱']
    hould_write_header = not header_exists(header)
    with open('通讯录.csv', 'at', encoding='utf-8') as f:
        csv_writer = csv.DictWriter(f,fieldnames=header)
        if hould_write_header:
            csv_writer.writeheader()  # write header
        csv_writer.writerows(rows)
        print("通讯录创建完成!")

# 2.  定义显示通讯录的函数
def show_contact():
    try:
        with open('通讯录.csv', 'rt',encoding='utf-8') as f:
            csv_reader = csv.DictReader(f,escapechar='\\')
            print('通讯录信息如下：')
            print('*' * 60)
            print(csv_reader.fieldnames)
            for row in csv_reader:
                print(row)
            print('*' * 60)
    except Exception as e:
        print(f"文件读取错误: {e}")

# 3. 定义按姓名查询联系人的函数
def search_contact():
    with open('通讯录.csv', 'rt',encoding='utf-8') as f:
        csv_reader = csv.DictReader(f, escapechar='\\')
        found = False
        query_name = input("请输入要查询的姓名：")
        for row in csv_reader:
            if row['姓名'] == query_name:
                print("找到的联系人信息如下：")
                for key, value in row.items():
                    print(f"{key}: {value}")
                found = True
                break
        if not found:
            print("未找到该联系人的信息!")

# 4. 定义按姓名删除联系人的函数
def delete_contact():
    with open('通讯录.csv', 'rt',encoding='utf-8') as f:
        csv_reader = csv.DictReader(f, escapechar='\\')
        contacts = list(csv_reader)  # 将所有联系人信息读取到列表中
        del_name = input("请输入要删除的姓名：")
        # 检查并删除联系人
        found = False
        new_contacts = [contact for contact in contacts if contact['姓名'] != del_name]
        if len(new_contacts) < len(contacts):
            found = True

        # 将更新后的数据写回CSV文件
        header = ['姓名', '手机号码', 'QQ号', '邮箱']
        if found:
            try:
                with open('通讯录.csv', 'wt', encoding='utf-8') as file:
                    writer = csv.DictWriter(file, fieldnames=header)
                    writer.writeheader()
                    writer.writerows(new_contacts)
                print(f"已删除姓名为'{del_name}'的联系人!")
            except Exception as e:
                print(f"写入文件时发生错误: {e}")
        else:
            print(f"未找到姓名为'{del_name}'的联系人!")

# 5.定义按姓名删除修改联系人信息的函数
def modify_contact():
    try:
        with open('通讯录.csv', 'rt',encoding='utf-8') as f:
            csv_reader = csv.DictReader(f, escapechar='\\')
            contacts = list(csv_reader)
            modi_name = input("请输入要修改的姓名：")
            found = False
            for contact in contacts:
                if contact['姓名'] == modi_name:
                    found = True
                    print(f"找到姓名为'{modi_name}'的联系人信息！")
                    print(contact)
                    while True:
                        field_to_modify = input("请输入要修改的字段名：")
                        if field_to_modify not in contact:
                            print(f"字段名'{field_to_modify}'不存在！")
                            return
                        new_value = input("请输入该字段的新值：")
                        contact[field_to_modify] = new_value
                        more_to_modify = input("还需要修改其他字段吗(Y/N)？")
                        if more_to_modify == 'Y' or more_to_modify == 'y':
                            continue
                        else:
                            break
                    print("联系人信息已更新！")
                    break

            if not found:
                print(f"未找到姓名为'{modi_name}'的联系人!")


            # 将更新后的数据写回CSV文件
            header = ['姓名', '手机号码', 'QQ号', '邮箱']
            with open('通讯录.csv', 'wt', encoding='utf-8') as file:
                writer = csv.DictWriter(file, fieldnames=header)
                writer.writeheader()
                writer.writerows(contacts)
                print("通讯录已更新!")
    except Exception as e:
        print(f"操作文件时发生错误: {e}")

# 6. 定义退出系统的函数
def exit_system():
    sys.exit()

# 在main函数中执行不同的功能
def main():
    while True:
        print_menu()  # 打印菜单
        key = input("请输入功能对应的数字：")  # 获取用户输入的序号
        if key == '1':  # 添加联系人
            create_contact()
        elif key == '2':  # 查看通讯录
            show_contact()
        elif key == '3':  # 删除联系人
            delete_contact()
        elif key == '4':  # 修改联系人
            modify_contact()
        elif key == '5':
            search_contact()   # 查询联系人
        elif key == '6':
            quit_confirm = input('确认退出？(Y or N):')
            if quit_confirm == 'Y' or quit_confirm == 'y':
               exit_system()
            else:
                print('输入有误，请重新输入!')

if __name__ == '__main__':
    main()